# -*- coding: utf-8 -*-
# @Date   : 2020/3/2
# @File   : R68_IC_UnpaidSmallLoanCnt_2D.py
# @Author : zhaochen
'''eof
name:未结清小额贷款笔数
code:R68_IC_UnpaidSmallLoanCnt_2D
tableName:
columnName:
groups:个人征信校验
dependencies:IC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''

import json
import sys
import re
import datetime
import pandas as pd
from datetime import datetime

reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']


def getTable(data, tableName, occurTimes, iteratorTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :param iteratorTimes:下级字段出现的次数，如果是0代表下级字段可以不出现，如果是1代表下级字段必须出现
        :return:该表全部数据  返回[{}]为异常缺失，返回0为正常缺失，其他返回正常数组
        '''
    try:
        table = data.get(tableName)
        if occurTimes == 0:
            if table is None or (table == "" and iteratorTimes == 0):
                return 0
            elif isinstance(table, list) is False or len(table) == 0 or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
        if occurTimes == 1:
            if table == "" and iteratorTimes == 0:
                return 0
            if table is None or isinstance(table, list) is False or len(table) == 0 \
                    or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
    except:
        return [{}]



# 统一转成datetime对象，只能转年月日的字符串
def date_format(time):
    r = re.compile(r'\D+')
    try:
        date = datetime.strptime(time, '%Y.%m.%d')
    except:
        try:
            date = datetime.strptime(time, '%Y-%m-%d')
        except:
            try:
                date = datetime.strptime(time, '%Y/%m/%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.strptime(tmp, '%Y%m%d')
                except:
                    date = None
    return date

def isfloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x)>=0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False

def R68_IC_UnpaidSmallLoanCnt_2D():
    data = IC_DSJ_2D.get('data')
    factor = []
    # 借贷账户信息 PDA[1.1]
    PDA = getTable(data, 'PDA', 1, 0)
    if PDA == [{}]:
        return u'缺失值'
    elif PDA == 0:
        return 0
    else:
        # 借贷账户信息单元 PD01[0.*]
        PD01 = getTable(PDA[0], 'PD01', 0, 1)
        if PD01 == [{}]:
            return u'缺失值'
        elif PD01 == 0:
            return 0
        else:
            for i in PD01:
                # 基本信息段 PD01A[1.1]
                PD01A = getTable(i, 'PD01A', 1, 1)
                # 最新表现信息
                PD01B = getTable(i, 'PD01B', 1, 1)
                # 最近一次月度表现信息段
                PD01C = getTable(i, 'PD01C', 1, 1)
                if PD01A == [{}] or PD01B == [{}]:
                    factor.append(None)
                elif PD01A == 0:
                    factor.append(0)
                else:
                    # 账户类型
                    PD01AD01 = PD01A[0].get("PD01AD01")
                    # 业务管理机构类型
                    PD01AD02 = PD01A[0].get("PD01AD02")
                    # 账户状态
                    PD01BD01 = PD01B[0].get("PD01BD01")
                    PD01CD01 = PD01C[0].get('PD01CD01')
                    # 余额
                    PD01BJ01 = PD01B[0].get("PD01BJ01")
                    if PD01AD01 not in null_type_list and PD01AD02 not in null_type_list and PD01BJ01 not in null_type_list:
                        if PD01BD01 in null_type_list:
                            try:
                                PD01BD01 = PD01CD01
                            except:
                                PD01BD01 = ""
                            if PD01BD01 in null_type_list:
                                factor.append(None)
                            else:
                                if PD01AD01 == "D1" and PD01BD01 in ["1", "2", "4", "6", "7", "8"] and isfloat(PD01BJ01) and float(PD01BJ01) > 0 \
                                        and PD01AD02 in ["51", "24"]:
                                    factor.append(1)
                                elif PD01AD01 == "R1" and PD01BD01 in ["1", "2", "4", "5", "6", "8"] and isfloat(PD01BJ01) and float(PD01BJ01) > 0 \
                                        and PD01AD02 in ["51",  "24"]:
                                    factor.append(1)
                                elif PD01AD01 == "R4" and PD01BD01 in ["1", "2", "4", "6", "8"] and isfloat(PD01BJ01) and float(PD01BJ01) > 0 \
                                        and PD01AD02 in ["51", "24"]:
                                    factor.append(1)
                                else:
                                    factor.append(0)
                        else:
                            if PD01AD01 == "D1" and PD01BD01 in ["1", "2", "4", "6", "7", "8"] and isfloat(PD01BJ01) and float(PD01BJ01) > 0 \
                                    and PD01AD02 in ["51", "24"]:
                                factor.append(1)
                            elif PD01AD01 == "R1" and PD01BD01 in ["1", "2", "4", "5", "6", "8"] and isfloat(PD01BJ01) and float(PD01BJ01) > 0 \
                                    and PD01AD02 in ["51",  "24"]:
                                factor.append(1)
                            elif PD01AD01 == "R4" and PD01BD01 in ["1", "2", "4", "6", "8"] and isfloat(PD01BJ01) and float(PD01BJ01) > 0 \
                                    and PD01AD02 in ["51", "24"]:
                                factor.append(1)
                            else:
                                factor.append(0)
                    else:
                        factor.append(None)
    factor = [x for x in factor if x is not None]
    if len(factor) == 0:
        return u'缺失值'
    else:
        return sum(factor)

result = R68_IC_UnpaidSmallLoanCnt_2D()
